package com.startupwebapp.services.general;

import java.util.List;

import org.directwebremoting.annotations.Param;
import org.directwebremoting.annotations.RemoteMethod;
import org.directwebremoting.annotations.RemoteProxy;
import org.directwebremoting.spring.SpringCreator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.annotation.Secured;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.startupwebapp.core.domain.users.Person;
import com.startupwebapp.core.domain.users.PersonRole;
import com.startupwebapp.dao.PersonDAO;
import com.startupwebapp.services.PersonInfo;
import com.startupwebapp.services.PersonService;

@Service("personService")
@RemoteProxy(creator = SpringCreator.class, creatorParams = @Param(name = "personService", value = "personService"), name = "personService")
@Transactional
public class PersonServiceImpl implements PersonService {
	@Autowired
	private PersonDAO personDAO;

	@Secured( { "ROLE_ADMIN" })
	public void changeRoles(Integer personId, List<PersonRole> roles) {
		Person person = personDAO.findById(personId);
		person.setRoles(roles);
		personDAO.merge(person);
	}

	public void setPersonState(Integer personId, boolean stateCode) {
		Person person = personDAO.findById(personId);
		person.setActive(stateCode);
		personDAO.merge(person);
	}

	public Person findPersonById(Integer personId) {
		return personDAO.findById(personId);
	}

	@Secured( { "ROLE_ADMIN" })
	public List<Person> findAll() {
		return personDAO.findAll();
	}

	public Person findByLogin(String login) {
		return personDAO.findByLogin(login);
	}

	@SuppressWarnings("unchecked")
	@Secured( { "ROLE_ADMIN" })
	public List<Person> get(int first, int amount) {
		return (List<Person>) personDAO.get(first, amount);
	}

	@Secured("ROLE_ADMIN")
	public int countAll() {
		return personDAO.countAll();
	}

	@Secured( { "ROLE_ADMIN" })
	public int count(boolean state) {
		return personDAO.count(state);
	}

	public void savePerson(Person person) {
		personDAO.save(person);
	}

	@RemoteMethod
	public String getCurrentLoggedInUserName() {
		return PersonInfo.getLogedInUserName();
	}

	@Secured("ROLE_ADMIN")
	public List<Person> findByActiveState(boolean state) {
		return personDAO.find(state);
	}
}
